<template>
  <div class="mainsu">
    <div class="main_white padding10">
      <div class="mainor_form batch-wrap">
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="90px"
          id="form"
        >
          <el-form-item label="商品名称：" prop="name">
            <el-input
              v-model.trim="form.name"
              placeholder="商品名称"
              clearable
              class="wid220"
            ></el-input>
          </el-form-item>
          <el-form-item label="分类：" prop="category_id" class="wid220">
            <el-cascader
              v-model="form.category_id"
              :options="options"
              :props="defaultProps"
              @change="getArticleList"
            ></el-cascader>
          </el-form-item>
          <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
            </MainFormBtn>
        </el-form>

        <!-- <div class="mainor_te">
          <el-button class="mainor_tea" @click="deleteId(1)"
            >批量删除商品</el-button
          >
          <el-button class="mainor_tea" @click="deleteId(2)"
            >一键清空回收站</el-button
          >
        </div> -->
      </div>
      <div class="main_table mg-t-6" :style="{ height: borderHeight + 'px' }">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.data"
          element-loading-text="加载中"
          fit
          highlight-current-row
          @select="selectApi"
          @select-all="selectAllApi"
          :height="borderHeight"
          :header-cell-style="tableHeightStyle"
        >
          <el-table-column type="selection" width="60"> </el-table-column>
          <el-table-column label="序号" width="60">
            <template slot-scope="scope">{{
              (current.page - 1) * current.per_page + scope.$index + 1
            }}</template>
          </el-table-column>
          <el-table-column
            label="名称"
            prop="name"
            width="300"
            show-overflow-tooltip
          >
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column
            label="别名"
            prop="byname"
            class-name="main_hei"
            show-overflow-tooltip
          />
          <el-table-column label="图片" class-name="main_hei">
            <template slot-scope="scope">
              <div class="demo-image__error mainor_im">
                <el-image
                  fit="fill"
                  :src="scope.row.pic"
                  :preview-src-list="scope.row.pics"
                >
                  <div slot="error" class="image-slot">
                    <img :src="puzzleImg" />
                  </div>
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="分类"
            prop="userNickname"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope"
              >{{ scope.row.category_p ? scope.row.category_p.title : "" }}|{{
                scope.row.category ? scope.row.category.title : ""
              }}</template
            >
          </el-table-column>
          <el-table-column
            label="编码"
            prop="goods_code"
            class-name="main_hei"
          />
          <el-table-column
            label="删除时间"
            prop="delete_time"
            class-name="main_hei"
          >
            <template slot-scope="scope">
              {{ new Date(scope.row.updated_at * 1000).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column
            label="管理操作"
            align="center"
            fixed="right"
            width="140"
            class-name="main_hei"
          >
            <template slot-scope="scope">
              <el-link type="warning" @click="knotClick(scope.row.id)"
                >恢复</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="main_page boxdq">
        <div></div>
        <!-- 分页 -->
        <div class="main_page_r">
          <MainPagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>

    <el-dialog title="是否删除" :visible.sync="dialogVisible" width="30%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div style="margin-left: 20px; margin-bottom: 20px">
          请在下面输入框中输入[<span style="color: red">{{
            selectKey == "1" ? "确认删除选中商品" : "确认删除全部商品"
          }}</span
          >]，删除后商品无法恢复！
        </div>
        <el-form-item label="请输入" prop="input">
          <el-input
            v-model="ruleForm.input"
            placeholder="请填写红色字体的内容！"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import { mapGetters } from "vuex";
import {
  recycle_goods,
  recycle_recycleGoods,
  setDelGoods,
} from "@/api/global/globalRecycle";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { puzzleImg } from "@/api/currency";
import { recursion, category } from "@/utils/index";

export default {
  mixins: [mixins],
  computed: {
    ...mapGetters(["avatar"]),
  },
  components: {},
  data() {
    const validatePass = (rule, value, callback) => {
      if (
        (this.selectKey == 1 && value !== "确认删除选中商品") ||
        (this.selectKey == 2 && value !== "确认删除全部商品")
      ) {
        callback(new Error("请填写红色字体的内容！"));
      } else {
        callback();
      }
    };

    return {
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: [],
      },
      puzzleImg,
      listLoading: false,
      // 搜索
      form: {
        name: "",
        pid: "",
        category_id: [],
      },
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },

      // 需要删除的商品
      deleteList: [],
      dialogVisible: false,
      selectKey: null,
      ruleForm: {
        input: null,
      },
      rules: {
        input: [{ required: true, trigger: "blur", validator: validatePass }],
      },
    };
  },
  created() {
    // 列表
    this.getNumerical(200);
    this.recycle_goods();
  },
  methods: {
    reset() {
      this.$refs['userListFrom'].resetFields()
      this.recycle_goods();
    },
    startGetting() {
      this.getArticleList();
    },
    // 恢复
    knotClick(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      recycle_recycleGoods(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "恢复成功",
            type: "success",
          });
          this.recycle_goods();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.recycle_goods();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.recycle_goods();
    },
    changePage(page) {
      this.current.page = page;
      this.recycle_goods();
    },
    // 列表
    recycle_goods() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      recycle_goods(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          res.data.list.data.map((e) => {
            if (e.images.length != 0) {
              e.images.map((a) => {
                a.path = this.avatar.domain + a.path;
                if (a.main == 1) {
                  e.pic = a.path;
                }
              });
              e.pics = e.images.map((s) => s.path);
            } else {
              e.pic = "";
              e.pics = [];
            }
          });
          this.list = res.data.list;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },

    // 勾选商品函数,获取需要删除的商品
    selectApi(selection, row) {
      this.deleteList = selection;
    },
    selectAllApi(selection) {
      console.log(selection);
      this.deleteList = selection;
    },

    // 批量删除商品
    deleteId(key) {
      if (this.deleteList.length == this.totalCount) {
        this.selectKey = 2;
      } else {
        this.selectKey = key;
      }
      // 代表批量删除商品
      if (key == 1) {
        if (this.deleteList.length == 0) {
          this.$message.error("请先勾选需要删除的商品!");
          return;
        }
      }
      this.dialogVisible = true;
    },
    save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let ids = this.deleteList.map((item) => item.id).join(",");
          let data = {
            ids: this.selectKey == 1 ? ids : "all",
          };
          let query = this.packageApi(data);
          setDelGoods(query).then((res) => {
            if (res.errcode == 0) {
              this.dialogVisible = false;
              this.listLoading = true;
              this.recycle_goods();
              this.deleteList = [];
              this.$refs.ruleForm.resetFields();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        } else {
          return false;
        }
      });
    },

    // 封装请求的sign和timeStamp字段
    packageApi(data = {}) {
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      return query;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 160px);
  }

  .mainor_form {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
}

/deep/.el-form-item {
  margin-bottom: 0;
}
/deep/.main_table .el-table .cell {
  padding-left: 16px;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
